﻿#region NeoPatterns
// 
// NeoPatterns framework is released under LGPLv3 license.
// See http://www.opensource.org/licenses/lgpl-3.0.html for more details.
// 
// Please visit http://neopatterns.wikidot.com for more information about NeoPatterns
// 
// Copyright (c) Pascal Craponne 2008
// 
#endregion

using System;
using System.Reflection;

namespace NeoPatterns.Core.Aop
{
    public class AttributePointcut : IPointcut
    {
        public Type AttributeType { get; set; }

        public bool Select(Type type, string objectName)
        {
            // to determine if we want to hook this type, we simply enumerate of its members (methods+properties)
            // if we can Select() one of them, we need to select the class
            foreach (var memberInfo in type.GetMembers(BindingFlags.Instance | BindingFlags.FlattenHierarchy))
            {
                if (memberInfo is FieldInfo)
                    continue;
                if (memberInfo is ConstructorInfo)
                    continue;
                if (Select(memberInfo))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// A member is selected it contains the requested attributes
        /// </summary>
        /// <param name="memberInfo"></param>
        /// <returns></returns>
        public bool Select(MemberInfo memberInfo)
        {
            return memberInfo.GetCustomAttributes(AttributeType, false).Length > 0;
        }
    }
}